<?php

namespace app\admin\controller;

use tencentLive\tencentapi;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Queue;

class Manage extends Common
{
    /**
     * 列表示例
     * */
    public function listDemo()
    {
        $list = Db::name('menu')->paginate(2);
        $this->assign('list', $list);

        $this->assign('title', '列表示例');
        return $this->fetch();
    }

    /**
     * 列表导出示例
     * */
    public function exportListDemo()
    {
        $title = '文件名';
        $th = ['标题一', '标题二', '标题三'];
        $td = ['key1', 'key2', 'key3'];
        $data = [
            [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ], [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ]
        ];

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 表单示例
     * */
    public function formDemo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            echo "<pre>";
            print_r($input);
            exit;
        }
        $this->assign('title', '表单示例');
        return $this->fetch();
    }

    /**
     * 视频分片上传示例
     * */
    public function uploadVideo()
    {
        $this->assign('title', '视频分片上传示例');
        return $this->fetch();
    }

    /**
     * 统计图示例
     * */
    public function chartDemo()
    {
        $this->assign('title', '统计图');
        return $this->fetch();
    }

    /**
     * 树形列表示例
     * */
    public function treeDemo()
    {
        return $this->fetch();
    }

    public function test()
    {
        return $this->view->fetch();
    }

    /**
     * 树状图原始demo
     * */
    public function tree()
    {
        $this->assign('title', 'test');
        return $this->fetch();
    }

    /**
     * iconfont
     * */
    public function iconfont()
    {
        $this->assign('title', 'iconfont');
        return $this->fetch();
    }

    /**
     * 文章分类列表
     * */
    public function articleTypeList()
    {
        $list = Db::name('article_type')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '文章分类列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章分类
     * */
    public function doArticleType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('article_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该分类已存在');

            $data = [
                'name' => $name
            ];

            if ($id > 0) {
                $res = Db::name('article_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('article_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '新增文章分类失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('article_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '文章分类');

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章分类
     * */
    public function delArticleType()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '分类ID缺失');

        $info = Db::name('article_type')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article_type')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 文章列表
     * */
    public function articleList()
    {
        $list = Db::name('article')->order('sort asc')->paginate()->each(function ($v) {
            $type_info = Db::name('article_type')->where(['id' => $v['type_id']])->find();
            $v['type_name'] = $type_info['name'];

            return $v;
        });

        $type_list = Db::name('article_type')->select();

        $this->assign('list', $list);
        $this->assign('type_list', $type_list);
        $this->assign('title', '文章列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章
     * */
    public function doArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $title = $input['title'];
            $vice_title = $input['vice_title'];
            $img = $input['img'];
            $type_id = $input['type_id'];
            $user_id = $input['user_id'];
            $sort = $input['sort'];
            $content = $input['content'];

            if (empty($title)) adminReturn(2, '请输入标题');
            if (empty($vice_title)) adminReturn(2, '请输入副标题');
            if (empty($img)) adminReturn(2, '请上传封面图');
            if (empty($type_id)) adminReturn(2, '请选择分类');
            if (empty($user_id)) adminReturn(2, '请选择作者');
            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'title' => $title,
                'vice_title' => $vice_title,
                'img' => $img,
                'type_id' => $type_id,
                'user_id' => $user_id,
                'sort' => $sort,
                'content' => $content
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('articleList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('articleList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('article')->where(['id' => $id])->find();
            }

            $type_list = Db::name('article_type')->select();

            $user_list = Db::name('user')->select();

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '文章');
            $this->assign('info', $info);
            $this->assign('type_list', $type_list);
            $this->assign('user_list', $user_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章
     * */
    public function delArticle()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '文章ID缺失');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 规格-属性 列表
     * */
    public function skuList()
    {
        $list = Db::name('sku')->select();
        $this->assign('list', json_encode($list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '规格-属性');
        return $this->fetch();
    }

    /**
     * 新增/编辑 规格-属性
     * */
    public function doSku()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $pid = $input['pid'];
            $name = $input['name'];

            if (empty($name)) apiReturn(2, '请输入名称');

            if ($id) {
                $where['name'] = $name;
                $where['id'] = ['neq', $id];
                if ($pid) {
                    $where['pid'] = $pid;
                } else {
                    $where['pid'] = 0;
                }
                $count = Db::name('sku')->where($where)->count();

                $obj = $pid ? '属性' : '规格';
                if ($count > 0) apiReturn(2, '该' . $obj . '名称已存在');

                //编辑
                $data = [
                    'name' => $name,
                    'pid' => $pid
                ];

                $res = Db::name('sku')->where(['id' => $id])->cache('sku')->update($data);
                if ($res) {
                    apiReturn(1, '编辑成功');
                } else {
                    apiReturn(2, '编辑失败');
                }
            } else {
                $where['name'] = $name;
                if ($pid) {
                    $where['pid'] = $pid;
                } else {
                    $where['pid'] = 0;
                }

                $count = Db::name('sku')->where($where)->count();

                $obj = $pid ? '属性' : '规格';
                if ($count > 0) apiReturn(2, '该' . $obj . '名称已存在');

                //新增
                $data = [
                    'name' => $name,
                    'pid' => $pid
                ];

                $res = Db::name('sku')->insert($data);
                if ($res) {
                    cache('sku', null);
                    apiReturn(1, '新增成功');
                } else {
                    apiReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) {
                $info = Db::name('sku')->where(['id' => $id])->find();
            } else {
                $info = [];
            }

            $sku_list = Db::name('sku')->where(['pid' => 0])->select();

            $data = [
                'info' => $info,
                'sku_list' => $sku_list
            ];

            apiReturn(1, '获取数据成功', $data);
        }

    }

    /**
     * 删除 规格-属性
     * */
    public function delSku()
    {
        $input = Request()->param();

        $id = $input['id'];
        $pid = $input['pid'];

        $obj = $pid ? '属性' : '规格';
        if (empty($id)) apiReturn(2, $obj . 'ID缺失');

        Db::startTrans();
        try {
            Db::name('sku')->where(['id' => $id])->cache('sku')->delete();
            if ($pid == 0) Db::name('sku')->where(['pid' => $id])->delete();

            Db::commit();
            apiReturn(1, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 商品分类列表
     * */
    public function goodsTypeList()
    {
        $list = Db::name('goods_type')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img_path'] = getPicture($v['img']);
            }
        }

        $this->assign('list', json_encode($list, JSON_UNESCAPED_UNICODE));
        $this->assign('title', '商品分类列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 商品分类
     * */
    public function doGoodsType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $pid = $input['pid'];
            $img = $input['img'] ? $input['img'] : 0;
            $name = $input['name'];

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($pid) $where['pid'] = $pid;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('goods_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该分类已存在');

            $data = [
                'pid' => $pid,
                'name' => $name,
                'img' => $img
            ];

            if ($id > 0) {
                $res = Db::name('goods_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑商品分类成功', url('goodsTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('goods_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增商品分类成功', url('goodsTypeList'));
                } else {
                    adminReturn(2, '新增商品分类失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('goods_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '商品分类');

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章分类
     * */
    public function delGoodsType()
    {
        $input = Request()->param();

        $id = $input['id'];
        $pid = $input['pid'];

        if (empty($id)) adminReturn(2, '分类ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('goods_type')->where(['id' => $id])->find();
            if ($info) {
                Db::name('goods_type')->where(['id' => $id])->delete();
                if ($pid == 0) Db::name('goods_type')->where(['pid' => $id])->delete();

                Db::commit();
                adminReturn(1, '删除成功');
            } else {
                Db::rollback();
                adminReturn(2, '数据不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 运费模板
     * */
    public function freightList()
    {
        $list = Db::name('freight')->paginate();


        $this->assign('list', $list);
        $this->assign('title', '运费模板');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 运费模板
     * */
    public function doFreight()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $type = $input['type'];
            $init_count = $input['init_count'];
            $init_count_price = $input['init_count_price'];
            $inc_count = $input['inc_count'];
            $inc_count_price = $input['inc_count_price'];
            $init_weight = $input['init_weight'];
            $init_weight_price = $input['init_weight_price'];
            $inc_weight = $input['inc_weight'];
            $inc_weight_price = $input['inc_weight_price'];
            $diff_freight = $input['diff_freight'];

            if (empty($name)) apiReturn(2, '请输入模板名称');

            $where['name'] = $name;
            if ($id > 0) $where['id'] = ['neq', $id];
            $count = Db::name('freight')->where($where)->count();
            if ($count > 0) adminReturn(2, '模板名称已存在');


            if (($type == 1 && (empty($init_count) || empty($init_count_price) || empty($inc_count) || empty($inc_count_price)))
                ||
                ($type == 2 && (empty($init_weight) || empty($init_weight_price) || empty($inc_weight) || empty($inc_weight_price)))
            ) adminReturn(2, '请完善计价规格');

            $time = time();
            $data = [
                'name' => $name,
                'type' => $type,
                'init_count' => $init_count,
                'init_count_price' => $init_count_price,
                'inc_count' => $inc_count,
                'inc_count_price' => $inc_count_price,
                'init_weight' => $init_weight,
                'init_weight_price' => $init_weight_price,
                'inc_weight' => $inc_weight,
                'inc_weight_price' => $inc_weight_price,
                'diff_freight' => $diff_freight,
            ];

            if ($id > 0) {
                // 编辑
                $data['update_time'] = $time;
                $res = Db::name('freight')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('freightList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                // 新增
                $data['create_time'] = $time;
                $res = Db::name('freight')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('freightList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('freight')->where(['id' => $id])->find();

            $province_list = Db::name('province')->field('province_id,name province_name')->select();
            if ($province_list) {
                foreach ($province_list as &$v) {
                    $city_list = Db::name('city')->field('city_id,name city_name')->where(['province_id' => $v['province_id']])->select();
                    $v['city_list'] = $city_list;
                }
            }

            $info['diff_freight_list'] = json_decode($info['diff_freight'], true);
            $this->assign('diff_freight_data', $info['diff_freight'] ? $info['diff_freight'] : json_encode([]));
            $this->assign('info', $info);
            $this->assign('province_list', $province_list);
            $this->assign('title', ($id ? '编辑' : '新增') . '运费模板');
            return $this->view->fetch();
        }
    }

    /**
     * 服务保障
     * */
    public function serviceGuarantee()
    {
        if (Request()->isPost()) {
            $service_guarantee = Request()->param('service_guarantee');

            $res = Db::name('goods_service_guarantee')->where(' 1 = 1 ')->setField(['service_guarantee' => $service_guarantee]);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $service_guarantee = Db::name('goods_service_guarantee')->value('service_guarantee');

            $this->assign('service_guarantee', json_decode($service_guarantee, true));
            $this->assign('title', '服务保障');
            return $this->view->fetch();
        }
    }

    /**
     * 商品列表
     * */
    public function goodsList()
    {
        $input = Request()->param();

        $one_type_id = $input['one_type_id'];
        $two_type_id = $input['two_type_id'];

        if ($one_type_id) $where['one_type_id'] = $one_type_id;
        if ($two_type_id) $where['two_type_id'] = $two_type_id;

        $list = Db::name('goods')->where($where)->order('create_time desc')->paginate()->each(function ($item) {
            $item['one_type_name'] = Db::name('goods_type')->where(['id' => $item['one_type_id']])->value('name');
            $item['two_type_name'] = Db::name('goods_type')->where(['id' => $item['two_type_id']])->value('name');

            return $item;
        });

        $type_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => 0])->select();
        if ($type_list) {
            foreach ($type_list as &$v) {
                $son_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => $v['id']])->select();
                $v['son_list'] = $son_list;
            }
        }
        $this->assign('list', $list);

        $this->assign('type_list', $type_list);
        $this->assign('type_list_json', json_encode($type_list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '商品列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 商品
     * */
    public function doGoods()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            Db::startTrans();
            try {
                //参数处理
                parse_str($input['form'], $form);

                $price_arr = [];
                if ($form['skus']) {
                    foreach ($form['skus'] as $v) {
                        if ($v['status'] == 1) $price_arr[] = $v['price'];
                    }
                }

                $min_price = min($price_arr);
                $max_price = max($price_arr);

                $skus = $form['skus'];
                unset($form['skus']);

                $id = $form['id'];

                if (empty($form['name'])) adminReturn(2, '请输入商品名称');
                if (empty($form['img'])) adminReturn(2, '请上传封面图');
                if (empty($form['content'])) adminReturn(2, '请输入商品介绍');
                $time = time();

                $data = [
                    'name' => $form['name'],
                    'img' => $form['img'],
                    'imgs' => $form['imgs'],
                    'one_type_id' => $form['one_type_id'],
                    'two_type_id' => $form['two_type_id'],
                    'skus' => $input['skus'],
                    'min_price' => $min_price >= 0 ? $min_price : 0,
                    'max_price' => $max_price >= 0 ? $max_price : 0,
                    'product_param' => $form['product_param'] ? $form['product_param'] : '',
                    'user_instructions' => $form['user_instructions'],
                    'content' => $form['content']
                ];

                if ($id > 0) {
                    $activity_count = Db::name('activity_log')->where(['goods_id' => $id])->count();
                    if ($activity_count) adminReturn(2, '该商品活动未结束，无法编辑');

                    //编辑
                    $data['update_time'] = $time;

                    Db::name('goods')->where(['id' => $id])->update($data);

                    Db::name('sku_value')->where(['goods_id' => $id])->delete();

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $id;

                            if ($v['picture']) {
                                $picture_info = Db::name('picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('sku_value')->insertAll($sku_value);
                    }

                    //此行请勿删除
                    cache('sku_' . $id, null);

                    Db::commit();
                    adminReturn(1, '编辑商品成功', url('goodsList'));
                } else {
                    //新增
                    $data['create_time'] = $time;

                    $goods_id = Db::name('goods')->insertGetId($data);

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $goods_id;

                            if ($v['picture']) {
                                $picture_info = Db::name('picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('sku_value')->insertAll($sku_value);
                    }

                    Db::commit();
                    adminReturn(1, '新增商品成功', url('goodsList'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~' . $e);
            }
        } else {
            $id = Request()->param('id');

            $info = Db::name('goods')->where(['id' => $id])->find();
            $info['imgs_arr'] = doImgs($info['imgs']);
            $info['product_param'] = json_decode($info['product_param'], true);

            $type_list = Db::name('goods_type')->field('id,name')->where(['pid' => 0])->select();
            if ($type_list) {
                foreach ($type_list as &$v) {
                    $son_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => $v['id']])->select();
                    $v['son_list'] = $son_list;
                }
            } else {
                $type_list = [];
            }

            $sku_list = Db::name('sku')->field('id,name title')->where(['pid' => 0])->cache('sku')->select();
            if ($sku_list) {
                //$skus_id_arr：所有属性的id集合
                $skus_id_arr = [];

                foreach ($sku_list as &$v) {
                    if ($id > 0) {
                        $sku_value_list = Db::name('sku_value')->field('sku_id')->where(['goods_id' => $id])->select();

                        if ($sku_value_list) {
                            foreach ($sku_value_list as &$val) {
                                $sku_id = explode('-', $val['sku_id']);
                                if ($sku_id) {
                                    foreach ($sku_id as &$value) {
                                        if (!in_array($value, $skus_id_arr)) {
                                            $skus_id_arr[] = $value;
                                        }
                                    }
                                }
                            }
                        }

                        $parent_list = Db::name('sku')->distinct(true)->field('pid')->where(['id' => ['IN', $skus_id_arr]])->select();
                        $parent_ids = array_column($parent_list, 'pid');

                        $v['checked'] = false;
                        if (in_array($v['id'], $parent_ids)) $v['checked'] = true;
                    } else {
                        $v['checked'] = false;
                    }

                    $child = Db::name('sku')->field('id,name title')->where(['pid' => $v['id']])->select();
                    if ($child) {
                        foreach ($child as &$val) {
                            $val['checked'] = in_array($val['id'], $skus_id_arr) ? true : false;
                        }
                    }
                    $v['child'] = $child;
                }
            }

            $this->assign('title', $id ? '编辑商品' : '新增商品');

            $this->assign('info', $info);
            $this->assign('type_list', $type_list);
            $this->assign('type_list_json', json_encode($type_list, JSON_UNESCAPED_UNICODE));
            $this->assign('sku_list', json_encode($sku_list, JSON_UNESCAPED_UNICODE));
            return $this->fetch();
        }
    }

    /**
     * 删除商品
     * */
    public function delGoods()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '商品ID缺失');

        $info = Db::name('goods')->where(['id' => $id])->find();
        if ($info) {
            $activity_count = Db::name('activity_log')->where(['goods_id' => $id])->count();
            if ($activity_count) adminReturn(2, '该商品活动未结束，无法删除');

            $res = Db::name('goods')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 团购活动
     * */
    public function groupList()
    {
        $list = Db::name('group')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '团购活动');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 团购
     * */
    public function doGroup()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $goods_id = $input["goods_id"];
            $start_time = strtotime($input["start_time"]);
            $end_time = strtotime($input["end_time"]) + 24 * 3600 - 1;
            $people_number = $input["people_number"];
            $time_limit = $input["time_limit"];
            $group_price = $input["group_price"];
            $chief_price = $input["chief_price"];
            $group_limit_number = $input["group_limit_number"];

            $time = time();

            if (empty($goods_id)) apiReturn(2, '请选择商品');
            if (empty($start_time) && empty($end_time)) adminReturn(2, "请选择拼团时间");
            if ($end_time <= $time || $end_time <= $start_time) adminReturn(2, '结束拼团时间有误，请重新设置');
            if (empty($people_number)) adminReturn(2, "请输入拼团人数");
            if (empty($time_limit)) adminReturn(2, "请输入拼团时限");
            if (empty($group_price)) adminReturn(2, "请输入成团价格");
            if (empty($chief_price)) adminReturn(2, "请输入团长价格");
            if (empty($group_limit_number)) adminReturn(2, "请输入限制成团数");

            Db::startTrans();
            try {
                $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();
                if (empty($goods_info)) adminReturn(2, '商品不存在或已删除');

                $data = [
                    'one_type_id' => $goods_info['one_type_id'],
                    'two_type_id' => $goods_info['two_type_id'],
                    'brand_id' => $goods_info['brand_id'],
                    'goods_name' => $goods_info['name'],
                    'goods_id' => $goods_id,
                    "start_time" => $start_time,
                    "end_time" => $end_time,
                    "people_number" => $people_number,
                    "time_limit" => $time_limit,
                    "group_price" => $group_price,
                    "chief_price" => $chief_price,
                    "group_limit_number" => $group_limit_number,
                ];

                if ($id > 0) {
                    $data['update_time'] = $time;
                    Db::name('group')->where(['id' => $id])->update($data);
                } else {
                    $data['create_time'] = $time;
                    $group_id = Db::name('group')->insertGetId($data);

                    Db::name('activity_log')->insert(['goods_id' => $goods_id, 'type' => 1]);

                    if ($group_id) {
                        $job_name = 'app\index\job\JobActivity';
                        $queue_name = "JobActivity";
                        $job_data = [
                            'obj_id' => $group_id,
                            'type' => 'group',
                        ];

                        if ($start_time > $time) {
                            // 未开始

                            // 新增开始团购活动任务
                            $job_data['node'] = 'start';
                            $start_task = Queue::later($start_time - $time, $job_name, $job_data, $queue_name);
                            if (!($start_task !== false)) {
                                Db::rollback();
                                adminReturn(2, '团购开始任务新增失败');
                            }
                        }

                        // 新增结束团购活动任务
                        $job_data['node'] = 'end';
                        $end_task = Queue::later($end_time - $time, $job_name, $job_data, $queue_name);
                        if (!($end_task !== false)) {
                            Db::rollback();
                            adminReturn(2, '团购结束任务新增失败');
                        }
                        Db::commit();
                        adminReturn(1, '提交成功', url('groupList'));
                    } else {
                        adminReturn(2, '提交失败');
                    }
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('group')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '团购');

            $activity_log = Db::name('activity_log')->field('goods_id')->select();
            $activity_goods_ids = array_column($activity_log, 'goods_id');
            if ($activity_goods_ids) $where['id'] = ['NOT IN', $activity_goods_ids];

            $goods_list = Db::name('goods')->field('id,name')->where(['activity_type' => 0, 'upper' => 1])->where($where)->select();
            $this->assign('goods_list', $goods_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除团购
     * */
    public function delGroup()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '团购ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('group')->where(['id' => $id])->find();

            if ($info) {
                Db::name('group')->where(['id' => $id])->delete();

                Db::name('goods')->where(['id' => $info['goods_id']])->setField('activity_type', 0);

                Db::name('activity_log')->where(['goods_id' => $info['goods_id']])->delete();

                $start_job_payload = [
                    'job' => 'app\index\job\JobActivity',
                    'data' => [
                        'obj_id' => $id,
                        'type' => 'group',
                        'node' => 'start'
                    ]
                ];
                $have_start_job = Db::name('jobs')->where(['payload' => json_encode($start_job_payload, JSON_UNESCAPED_UNICODE)])->count();
                if ($have_start_job) Db::name('jobs')->where(['payload' => json_encode($start_job_payload, JSON_UNESCAPED_UNICODE)])->delete();

                $end_job_payload = [
                    'job' => 'app\index\job\JobActivity',
                    'data' => [
                        'obj_id' => $id,
                        'type' => 'group',
                        'node' => 'end'
                    ]
                ];
                $have_end_job = Db::name('jobs')->where(['payload' => json_encode($end_job_payload, JSON_UNESCAPED_UNICODE)])->count();
                if ($have_end_job) Db::name('jobs')->where(['payload' => json_encode($end_job_payload, JSON_UNESCAPED_UNICODE)])->delete();

                Db::commit();
                adminReturn(1, '删除成功');
            } else {
                Db::rollback();
                adminReturn(2, '团购活动不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试');
        }
    }

    /**
     * 秒杀活动
     * */
    public function seckillList()
    {
        $list = Db::name('seckill')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '秒杀活动');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 秒杀
     * */
    public function doSeckill()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $goods_id = $input["goods_id"];
            $start_time = strtotime($input["start_time"]);
            $end_time = strtotime($input["end_time"]);
            $price = $input["price"];
            $count = $input["count"];

            $time = time();

            if (empty($goods_id)) apiReturn(2, '请选择商品');
            if (empty($start_time) && empty($end_time)) adminReturn(2, "请选择拼团时间");
            if ($end_time <= $time || $end_time <= $start_time) adminReturn(2, '结束拼团时间有误，请重新设置');
            if (empty($goods_id)) adminReturn(2, "请选择秒杀商品");
            if (empty($price)) apiReturn(2, '请输入秒杀价格');
            if (empty($count)) apiReturn(2, '请输入秒杀数量');

            Db::startTrans();
            try {
                $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();
                if (empty($goods_info)) adminReturn(2, '商品不存在或已删除');

                $data = [
                    'one_type_id' => $goods_info['one_type_id'],
                    'two_type_id' => $goods_info['two_type_id'],
                    'brand_id' => $goods_info['brand_id'],
                    'goods_name' => $goods_info['name'],
                    "goods_id" => $goods_id,
                    "start_time" => $start_time,
                    "end_time" => $end_time,
                    "price" => $price,
                    "count" => $count,
                    "surplus_count" => $count
                ];

                if ($start_time >= $time) {
                    // 活动中

                    $data['status'] = 1;

                    Db::name('goods')->where(['goods_id' => $goods_id])->setField('activity_type', 2);
                } else {
                    // 未开始

                }

                if ($id > 0) {
                    $data['update_time'] = $time;
                    Db::name('seckill')->where(['id' => $id])->update($data);
                } else {
                    $data['create_time'] = $time;
                    Db::name('seckill')->insert($data);

                    Db::name('activity_log')->insert(['goods_id' => $goods_id, 'type' => 2]);
                }

                Db::commit();
                adminReturn(1, '提交成功', url('seckillList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('seckill')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '秒杀');

            $activity_log = Db::name('activity_log')->field('goods_id')->select();
            $activity_goods_ids = array_column($activity_log, 'goods_id');

            if ($activity_goods_ids) $where['id'] = ['NOT IN', $activity_goods_ids];

            $goods_list = Db::name('goods')->field('id,name')->where(['activity_type' => 0, 'upper' => 1])->where($where)->select();
            $this->assign('goods_list', $goods_list);


            return $this->view->fetch();
        }
    }

    /**
     * 删除秒杀活动
     * */
    public function delSeckill()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '秒杀活动ID缺失');

        $info = Db::name('seckill')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('seckill')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * banner列表
     */
    public function bannerList()
    {
        $list = Db::name('banner')->paginate();

        $this->assign('list', $list);
        $this->assign('title', 'banner列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 banner
     * */
    public function doBanner()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $type = $input["type"];
            $to_id = $input["to_id"];

            if (empty($img)) adminReturn(2, '请上传banner图');

            $data = [
                "img" => $img,
                "type" => $type,
                'to_id' => $to_id
            ];

            if ($id > 0) {
                $res = Db::name('banner')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '编辑banner失败或未编辑');
                }
            } else {
                $res = Db::name('banner')->insert($data);
                if ($res) {
                    adminReturn(1, '新增banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '新增banner失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('banner')->where(['id' => $id])->find();

            $goods_list = Db::name('goods')->field('id,name')->select();
            $this->assign('goods_list', $goods_list);
            $this->assign('goods_list_obj', json_encode($goods_list, JSON_UNESCAPED_UNICODE));

            $article_list = Db::name('article')->field('id,title name')->select();
            $this->assign('article_list_obj', json_encode($article_list, JSON_UNESCAPED_UNICODE));

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . 'banner');

            return $this->view->fetch();
        }
    }

    /**
     * 删除banner
     * */
    public function delBanner()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'bannerID缺失');

        $info = Db::name('banner')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('banner')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $order_number = $input['order_number'];
        $status = $input['status'];
        $after_status = $input['after_status'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($mobile)) $where["b.mobile"] = ["like", "%" . $mobile . "%"];
        if (!empty($order_number)) $where["a.order_number"] = ["like", "%" . $order_number . "%"];
        if (!empty($status)) $where["a.status"] = $status;
        if (!empty($after_status)) $where["a.after_status"] = $after_status;

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }
        $where["a.id"] = ["gt", 0];
        $list = Db::name('order a')->field("a.*,b.mobile,b.username")->join('user b', "a.user_id = b.id", "left")->where($where)->order('create_time desc')->paginate()->each(
            function ($v) {
                if ($v['status'] == 1) {
                    $v['status_text'] = "待付款";
                } elseif ($v['status'] == 2) {
                    $v['status_text'] = "待发货";
                } elseif ($v['status'] == 3) {
                    $v['status_text'] = "待收货";
                } elseif ($v['status'] == 4) {
                    $v['status_text'] = "待评价";
                } elseif ($v['status'] == 5) {
                    $v['status_text'] = "已完成";
                } elseif ($v['status'] == 7) {
                    $v['status_text'] = "售后中";
                } elseif ($v['status'] == 8) {
                    $v['status_text'] = "售后完成";
                } elseif ($v['status'] == 10) {
                    $v['status_text'] = "已取消";
                } else {
                    $v['status_text'] = "未知";
                }

                if ($v['after_status'] == 0) {
                    $v['after_status_text'] = "未售后";
                } elseif ($v['after_status'] == 1) {
                    $v['after_status_text'] = "售后中";
                } elseif ($v['after_status'] == 2) {
                    $v['after_status_text'] = "售后成功";
                } elseif ($v['after_status'] == 3) {
                    $v['after_status_text'] = "售后失败";
                } else {
                    $v['after_status_text'] = "未知";
                }

                if ($v['pay_type'] == 1) {
                    $v['pay_type_text'] = "微信支付";
                } elseif ($v['pay_type'] == 2) {
                    $v['pay_type_text'] = "收益支付";
                } else {
                    $v['pay_type_text'] = "未知";
                }
                return $v;
            }


        );
        $this->assign('list', $list);

        $all_pay_price = Db::name('order a')->join('user b', "a.user_id = b.id", "left")->where($where)->sum('pay_price');
        $this->assign('all_pay_price', sprintf('%.2f', $all_pay_price));

        $this->assign('title', '订单列表');

        return $this->fetch();
    }

    /**
     * 订单详情
     */
    public function doOrder()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input["id"];

            $order_info = Db::name("order")->where(["id" => $id])->find();
            if ($order_info['status'] == 2) {
                $status = 3;
                $express_id = $input["express_id"];
                $send_num = $input["send_num"];
                if (empty($send_num)) adminReturn(2, "请输入快递编号");
                Db::startTrans();
                $data = [
                    "status" => $status,
                    "express_id" => $express_id,
                    "send_num" => $send_num,
                ];

                $data['update_time'] = time();
                $res = Db::name('order')->where(['id' => $id])->update($data);
                if ($res) {
                    /** 添加发送消息 */
                    $data_msg = [
                        "user_id" => $order_info["user_id"],
                        "order_id" => $id,
                        "title" => "您的订单已经发货",
                        "content" => "您的订单已经发货",
                        "type" => 1,
                        "create_time" => time(),
                    ];
                    Db::name("msg")->insert($data_msg);

                    /** 添加15天自动确认收货计划 */
                    $time = time() + 24 * 3600 * C('CONFIRM_GET_DAY');
                    $data_plan = [
                        "user_id" => $order_info["user_id"],
                        "order_id" => $id,
                        "type" => 2,
                        "execute_date" => date('Y-m-d', $time),
                    ];
                    Db::name("plan")->insert($data_plan);

                    Db::commit();
                    adminReturn(1, '编辑成功', url('orderList'));
                } else {
                    Db::rollback();
                    adminReturn(2, '系统繁忙，请稍后再试');
                }
            } elseif ($order_info['status'] == 7) {
                $after_status = $input['after_status'];
                $after_refuse_reason = $input['after_refuse_reason'];
                if (empty($after_status)) adminReturn(2, '请选择售后操作');
                if ($after_status == 3 && empty($after_refuse_reason)) adminReturn(2, "请输入拒绝原因");

                $time = time();

                Db::startTrans();
                try {
                    $data = [
                        'back_order_sn' => $order_info['pay_order_sn'],
                        'status' => 8,//订单状态改成售后完成
                        'after_status' => $after_status,
                        'after_refuse_reason' => $after_refuse_reason,
                        'update_time' => $time
                    ];
                    Db::name('order')->where(['id' => $id])->update($data);

                    $price = $order_info['pay_price'];
                    /**
                     * @TODO 第5点暂时不做处理
                     * 同意售后【退货退款】（对应支付成功做退回处理）
                     * 1：金额原路退回（微信退款 || 收益退款）  注：如果是收益退款的话需要生成对应的收益记录，且用户可用收益增加
                     * 3：减少商品销量
                     * 4：增加商品库存
                     * 5：用户is_activation修改为已激活状态（1）【暂时不做处理】
                     * 6：冻结的直推、级差、服务津贴作废（作废）
                     * 7：删除自动确认收货任务
                     * 同意售后【换货】
                     * 1：订单变成待收货状态
                     * 2：删除原来的自动确认收货任务
                     * 3：新增自动确认收货任务
                     * */
                    if ($after_status == 2) {
                        // 同意售后

                        if ($input['after_type'] == '退货退款') {
                            $vice_order_info = Db::name('vice_order')->where(['order_id' => $id])->find();

                            // 1：金额原路退回
                            if ($order_info['pay_type'] == 1) {
                                //微信支付
                                Loader::import('wxpaysdk\wxPay', EXTEND_PATH);
                                $obj = new \wxPay();

                                $obj->refund($price, $price, $order_info['pay_order_sn'], $order_info['pay_order_sn'], $order_info['after_reason']);
                            } else {
                                $user_id = $order_info['user_id'];

                                $user_info = Db::name('user')->where(['id' => $user_id])->find();
                                $mobile = $user_info['mobile'] ? : '';
                                $gzh_openid = $user_info['gzh_openid'];

                                Db::name('user')->where(['id' => $user_id])->setInc('all_profit', $price);

                                //收益支付
                                $profit_data = [
                                    'order_id' => $id,
                                    'user_id' => $order_info['user_id'],
                                    'price' => $order_info['pay_price'],
                                    'type' => 12,
                                    'status' => 2,
                                    'create_time' => $time
                                ];
                                Db::name('profit')->insert($profit_data);

                                // 发送微信公众号模板消息
                                $template_msg = [
                                    'first' => [
                                        'value' => '您好，您的售后订单购物抵扣收益已退回',
                                        'color' => '#743A3A'
                                    ],
                                    'keyword1' => [
                                        'value' => '购物抵扣收益退款',
                                        'color' => '#743A3A'
                                    ],
                                    'keyword2' => [
                                        'value' => $price,
                                        'color' => '#743A3A'
                                    ],
                                    'keyword3' => [
                                        'value' => date('Y-m-d'),
                                        'color' => '#743A3A'
                                    ],
                                    'keyword4' => [
                                        'value' => '点击查看',
                                        'color' => '#743A3A'
                                    ],
                                    'remark' => [
                                        'value' => '',
                                        'color' => '#743A3A'
                                    ]
                                ];
                                $page = 'pages/my_income/my_income?user_id=' . $user_id . '&mobile=' . $mobile;
                                if ($gzh_openid && $price > 0) sendWxTemplateNotice($gzh_openid, $template_msg, 12, $page);
                            }

                            $buy_count = $vice_order_info['count'];
                            $goods_id = $vice_order_info['goods_id'];
                            $sku_id = $vice_order_info['sku_id'];

                            // 3：减少商品销量
                            $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();
                            if ($goods_info && $buy_count > 0) Db::name('goods')->where(['id' => $goods_id])->setDec('sales_count', $buy_count);

                            // 4：增加商品库存
                            $sku_info = Db::name('sku_value')->where(['goods_id' => $goods_id, 'sku_id' => $sku_id])->find();
                            if ($sku_info && $buy_count > 0) Db::name('sku_value')->where(['goods_id' => $goods_id, 'sku_id' => $sku_id])->setInc('stock', $buy_count);

                            // 6：冻结的直推、级差、服务津贴作废（作废）
                            $frozen_profit_list = Db::name('profit')->where(['order_id' => $id, 'type' => ['IN', [1, 2, 3]]])->select();
                            if ($frozen_profit_list) {
                                $update_profit_data = [
                                    'status' => -1,
                                    'update_time' => $time
                                ];
                                Db::name('profit')->where(['order_id' => $id, 'type' => ['IN', [1, 2, 3]]])->update($update_profit_data);
                            }

                            // 7：删除自动确认收货任务
                            Db::name('plan')->where(['order_id' => $id, 'type' => 2])->delete();
                        } else if ($input['after_type'] == '换货') {
                            // 1：订单变成待收货状态
                            $change_order_data = [
                                'status' => 3,
                                'update_time' => $time
                            ];
                            Db::name('order')->where(['id' => $id])->update($change_order_data);
                            // 2：删除原来的自动确认收货任务
                            Db::name('plan')->where(['order_id' => $id, 'type' => 2])->delete();
                            // 3：新增自动确认收货任务
                            $time = time() + 24 * 3600 * C('CONFIRM_GET_DAY');
                            $data_plan = [
                                "user_id" => $order_info["user_id"],
                                "order_id" => $id,
                                "type" => 2,
                                "execute_date" => date('Y-m-d', $time),
                            ];
                            Db::name("plan")->insert($data_plan);
                        }
                    }

                    Db::commit();
                    adminReturn(1, '操作成功', url('orderList'));
                } catch (\Exception $e) {
                    Db::rollback();
                    adminReturn(2, '系统繁忙，请稍后再试~');
                }
            }
        } else {
            $id = input("id");
            $order_info = Db::name('order a')->field("a.*,b.mobile,b.username")->where(["a.id" => $id])->join('user b', "a.user_id = b.id", "left")->find();
            $order_vice = Db::name("vice_order")->where(["order_id" => $id])->select();
            foreach ($order_vice as &$vo) {
                $suk_value_arr = explode("-", $vo['sku_id']);
                $suk_name_str = "";
                foreach ($suk_value_arr as $vv) {
                    $sku_info = Db::name("sku")->where(["id" => $vv])->find();
                    $sku_p_info = Db::name("sku")->where(["id" => $sku_info['pid']])->find();
                    $suk_name_str .= $sku_p_info['name'] . ": " . $sku_info['name'] . ";";
                }
                $vo['suk_name_str'] = $suk_name_str;
                $gift_ids_arr = explode("-", $vo['gift_ids']);

                /** 查看商品是不是有评论 */
                $is_have = Db::name('goods_comment')->where(["order_id" => $id, "goods_id" => $vv['goods_id']])->value("id");
                if ($is_have) {
                    $is_comment = $is_have;
                } else {
                    $is_comment = 0;
                }
                $vo['is_comment'] = $is_comment;
            }

            //查询出快递公司
            $express_list = Db::name("express")->field("id,name")->select();

            if ($express_id = $order_info['express_id']) $order_info['express_name'] = Db::name('express')->where(['id' => $express_id])->value('name');

            $this->assign('info', $order_info);
            $this->assign('order_vice', $order_vice);
            $this->assign('express_list', $express_list);

            $this->assign('title', '订单详情');
            return $this->fetch();
        }
    }

    /**
     *商品评论
     */
    public function doComment()
    {
        $input = Request()->param();
        $id = $input["id"];

        //查询出评论内容
        $info = Db::name('goods_comment')->where(["id" => $id])->find();

        $info["img_arr"] = explode(",", $info["imgs"]);

        $this->assign('info', $info);
        $this->assign('title', '评论详情');
        return $this->fetch();
    }

    /**
     * 公告列表
     */
    public function msgList()
    {
        $input = Request()->param();

        $title = $input['title'];
        $where["type"] = 3;
        if ($title) $where['title'] = ["like", '%' . $title . '%'];
        $list = Db::name('msg')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '公告列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 公告
     */
    public function doMsg()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input['id'];
            $title = $input["title"];
            $content = $input["content"];

            if (empty($title)) adminReturn(2, "请输入标题");
            if (empty($content)) adminReturn(2, "请填写公告内容");

            if ($id) {
                $data = [
                    'title' => $title,
                    'content' => $content
                ];

                $res = Db::name('msg')->where(['id' => $id])->update($data);
            } else {
                $data = [
                    "user_id" => 0,
                    "title" => $title,
                    "content" => $content,
                    "type" => 3,
                    "look_count" => 0,
                    "create_time" => time()
                ];

                $res = Db::name('msg')->insert($data);
            }

            if ($res) {
                adminReturn(1, ($id ? '编辑' : '新增') . '公告成功', url('msgList'));
            } else {
                adminReturn(2, ($id ? '编辑' : '新增') . '公告失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('msg')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '公告详情' : '新增公告'));

            return $this->view->fetch();
        }
    }

    /**
     * 删除公告
     */
    public function delMsg()
    {
        $input = Request()->param();

        $id = $input["id"];

        if ($id > 0) {
            $res = Db::name('msg')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除公告成功', url('msgList'));
            } else {
                adminReturn(2, '删除公告失败');
            }
        }
    }

    /**
     * 意见反馈
     */
    public function feedbackList()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $where["a.id"] = ["gt", "0"];

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('feedback a')->field("a.*,b.username")->join('user b', "a.user_id = b.id", "left")
            ->where($where)->order('a.create_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '意见反馈列表');

        return $this->fetch();
    }

    /**
     * 会员列表
     * */
    public function userList()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        $where['is_admin'] = 0;
        if ($mobile) $where['mobile'] = ['LIKE', '%' . $mobile . '%'];

        if (!empty($start_time) && empty($end_time)) {
            $where["create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('user')->where($where)->order('create_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '会员列表');

        return $this->fetch();
    }


    /**
     * 新增/编辑 会员
     */
    public function doUser()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input['id'];
            $mobile = $input["mobile"];
            $username = $input["username"];
            $password = $input["password"];
            $status = $input["status"];

            if (empty($mobile)) adminReturn(2, "请输入手机号");
            if (empty($username)) adminReturn(2, "请输入昵称");
            if (empty($id) && empty($password)) adminReturn(2, '请输入密码');

            $where['mobile'] = $mobile;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('user')->where($where)->count();
            if ($count) adminReturn(2, '手机号已被占用');

            $time = time();

            $data = [
                'mobile' => $mobile,
                'username' => $username,
                'password' => thinkEncrypt($password),
                'status' => $status
            ];

            if (empty($id)) {
                $data['surplus_video_time'] = C('USER_ALL_VIDEO_TIME') * 60;
                $data['failure_time'] = $time + 365 * 24 * 3600;
            }

            if ($id) {
                $data['update_time'] = $time;

                $res = Db::name('user')->where(['id' => $id])->update($data);
            } else {
                $data['create_time'] = $time;

                $res = Db::name('user')->insert($data);
            }

            if ($res) {
                adminReturn(1, ($id ? '编辑' : '新增') . '会员', url('userList'));
            } else {
                adminReturn(2, ($id ? '编辑' : '新增') . '会员');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('user')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '会员详情' : '注册会员'));

            return $this->view->fetch();
        }
    }

    /**
     * 会员续费
     * */
    public function renew()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $renew_time = $input['renew_time'];

        if (empty($user_id)) apiReturn(2, '用户id缺失');
        if (empty($renew_time)) apiReturn(2, '请输入续费时长');

        $info = Db::name('user')->where(['id' => $user_id])->find();
        if ($info) {
            $time = time();

            if ($info['failure_time'] > $time) {
                // 未到期续费
                $data = [
                    'failure_time' => $info['failure_time'] + 365 * 24 * 3600,
                    'surplus_video_time' => $info['surplus_video_time'] + $renew_time * 60,
                    'update_time' => $time
                ];
            } else {
                // 到期续费
                $data = [
                    'failure_time' => $time + 365 * 24 * 3600,
                    'surplus_video_time' => $renew_time * 60,
                    'update_time' => $time
                ];
            }

            $res = Db::name('user')->where(['id' => $user_id])->update($data);
            if ($res) {
                apiReturn(1, '续费成功');
            } else {
                apiReturn(2, '续费失败');
            }
        } else {
            apiReturn(2, '用户不存在或已删除');
        }
    }

    /**
     * 前景列表
     * */
    public function frontImgList()
    {
        $list = Db::name('front_img')->order('create_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '前景列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 前景
     * */
    public function doFrontImg()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $img = $input['img'];

            if (empty($img)) adminReturn(2, '请上传前景');

            $data = [
                'img' => $img
            ];

            if ($id > 0) {
                $data['update_time'] = time();
                $res = Db::name('front_img')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('frontImgList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $data['create_time'] = time();
                $res = Db::name('front_img')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('frontImgList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('front_img')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '前景');

            return $this->view->fetch();
        }
    }

    /**
     * 删除前景
     * */
    public function delFrontImg()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '前景ID缺失');

        $info = Db::name('front_img')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('front_img')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 背景列表
     * */
    public function behindImgList()
    {
        $list = Db::name('behind_img')->order('create_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '背景列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 背景
     * */
    public function doBehindImg()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $img = $input['img'];

            if (empty($img)) adminReturn(2, '请上传背景');

            $data = [
                'img' => $img
            ];

            if ($id > 0) {
                $data['update_time'] = time();
                $res = Db::name('behind_img')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('behindImgList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $data['create_time'] = time();
                $res = Db::name('behind_img')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('behindImgList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('behind_img')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '背景');

            return $this->view->fetch();
        }
    }

    /**
     * 删除背景
     * */
    public function delBehindImg()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '背景ID缺失');

        $info = Db::name('behind_img')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('behind_img')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 直播间列表
     * */
    public function liveList()
    {
        $list = Db::name('live')->order('create_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '直播间列表');

        return $this->fetch();
    }

    /**
     * 直播间详情
     * */
    public function doLive()
    {
        $id = Request()->param('id');

        if (empty($id)) $this->error('直播间ID缺失');

        $info = Db::name('live')->where(['id' => $id])->find();
        // 商品文案
        if ($goods_copywrite_json = $info['goods_copywrite_json']) {
            $goods_copywrite_arr = json_decode($goods_copywrite_json, true);
            $goods_copywrite_ids = array_column($goods_copywrite_arr, 'goods_copywrite_ids');
            $goods_copywrite_ids_str = implode(',', $goods_copywrite_ids);

            $goods_copywrite_list = Db::name('goods_copywrite')->where(['id' => ['IN', $goods_copywrite_ids_str]])->select();
        }
        $this->assign('goods_copywrite_list', $goods_copywrite_list ? : []);

        // 互动文案
        if ($interact_copywrite_ids = $info['interact_copywrite_ids']) {
            $interact_copywrite_list = Db::name('interact_copywrite')->where(['id' => ['IN', $interact_copywrite_ids]])->select();
        }
        $this->assign('interact_copywrite_list', $interact_copywrite_list ? : []);


        $this->assign('info', $info);
        $this->assign('title', '直播间详情');

        return $this->view->fetch();
    }

    /**
     * 数字人列表
     * */
    public function virtualmanList()
    {
        $list = Db::name('virtualman')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '数字人列表');

        return $this->fetch();
    }


    /**
     * 同步数字人
     * */
    public function updateVirtualmanAndTimbres()
    {
        $res = (new tencentapi())->getResource();
        $data = json_decode($res, true);

        try {
            $time = time();
            $code_arr = [];

            if ($data['Header']['Code'] == 0) {
                $VirtualmanResources = $data['Payload']['VirtualmanResources'];
                if ($VirtualmanResources) {
                    foreach ($VirtualmanResources as $v) {
                        if ($v['VirtualmanResourcesByAppKey']) {
                            $virtualmans_data = [];// 虚拟人数据
                            foreach ($v['VirtualmanResourcesByAppKey'] as $val) {
                                if ($val['Virtualmans']) {
                                    foreach ($val['Virtualmans'] as $value) {

                                        if ($value['Timbres']) {
                                            $timbres_data = [];
                                            foreach ($value['Timbres'] as $vv) {
                                                if (!in_array($vv['TimbreKey'], array_column($timbres_data, 'TimbreKey'))) {
                                                    $timbres_data[] = [
                                                        'timbre_key' => $vv['TimbreKey'],
                                                        'timbre_name' => $vv['TimbreName'],
                                                        'timbre_sample' => $vv['TimbreSample'],
                                                        'virtualman_key' => $value['VirtualmanKey'],
                                                        'create_time' => $time
                                                    ];
                                                }
                                            }
                                            if ($timbres_data) Db::name('virtualman_timbre')->insertAll($timbres_data);
                                        }

                                        $code_arr[] = $value['Code'];

                                        $virtualmans_data[] = [
                                            'name' => $value['Name'],
                                            'code' => $value['Code'],
                                            'clothes_name' => $value['ClothesName'],
                                            'pose_name' => $value['PoseName'],
                                            'header_image' => $value['HeaderImage'],
                                            'pose_image' => $value['PoseImage'],
                                            'clothes_image' => $value['ClothesImage'],
                                            'virtualman_key' => $value['VirtualmanKey'],
                                            'create_time' => $time
                                        ];
                                    }
                                }
                            }

                            $res = Db::name('virtualman')->where('1 = 1')->delete();
                            if ($res && $virtualmans_data) {
                                $res2 = Db::name('virtualman')->insertAll($virtualmans_data);
                            }
                        }
                    }
                }
            }

            if ($code_arr) {
                $code_arr = array_unique($code_arr);

                $virtualman_figure_data = [];
                foreach ($code_arr as $v) {
                    $anchor_res = (new tencentapi())->getresourcebyanchor(false, $v);
                    $anchor_data = json_decode($anchor_res, true);

                    if ($anchor_data['Header']['Code'] == 0) {
                        $VirtualmanResources = $anchor_data['Payload']['VirtualmanResources'];
                        if ($VirtualmanResources) {
                            foreach ($VirtualmanResources as &$val) {
                                $Virtualmans = $val['Virtualmans'];
                                if ($Virtualmans) {
                                    foreach ($Virtualmans as &$value) {
                                        $resolution = explode("x", $value['Resolution']);
                                        $type = $resolution[0] < $resolution[1] ? 1 : 2;

                                        $virtualman_figure_data[] = [
                                            'name' => $value['AnchorName'],
                                            'clothes_name' => $value['ClothesName'],
                                            'pose_name' => $value['PoseName'],
                                            'header_image' => $value['HeaderImage'],
                                            'pose_image' => $value['PoseImage'],
                                            'clothes_image' => $value['ClothesImage'],
                                            'virtualman_key' => $value['VirtualmanKey'],
                                            'type' => $type,
                                            'create_time' => $time
                                        ];
                                    }
                                }
                            }
                        }
                    }
                }
                $figure_res = Db::name('virtualman_figure')->where('1 = 1')->delete();
                if ($figure_res && $virtualman_figure_data) {
                    $res3 = Db::name('virtualman_figure')->insertAll($virtualman_figure_data);
                }
            }

            if ($res && $res2 && $res3) {
                Db::commit();
                adminReturn(1, '同步成功');
            } else {
                Db::rollback();
                adminReturn(2, '同步失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '同步失败');
        }
    }

    /**
     * 会员统计
     * */
    public function userCensus()
    {
        $time_list = Db::name('user')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->where(['is_admin' => 0])->order('create_time asc')->select();
        $user_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];

                $user_count = Db::name('user')->where(['is_admin' => 0])->where($where)->count();
                $user_list[] = $user_count;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('user_list', json_encode($user_list));

        $this->assign('title', '会员统计');

        return $this->fetch();
    }

    /**
     * 直播统计
     * */
    public function liveCensus()
    {
        $time_list = Db::name('live')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->order('create_time asc')->select();
        $live_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];

                $user_count = Db::name('live')->where($where)->count();
                $live_list[] = $user_count;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('live_list', json_encode($live_list));

        $this->assign('title', '直播统计');

        return $this->fetch();
    }

    /**
     * 视频生成统计
     * */
    public function videoCensus()
    {
        $goods_time_list = Db::name('goods_copywrite')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->order('create_time asc')->select();
        $interact_time_list = Db::name('interact_copywrite')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->order('create_time asc')->select();
        $time_list = array_unique(array_merge($goods_time_list, $interact_time_list));

        $video_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $where['is_del'] = 0;
                $where['video_status'] = 1;
                $where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];

                $goods_video_count = Db::name('goods_copywrite')->where($where)->count();
                $interact_video_count = Db::name('interact_copywrite')->where($where)->count();
                $video_list[] = $goods_video_count + $interact_video_count;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('video_list', json_encode($video_list));

        /***************************************/

        $where['is_del'] = 0;
        $where['video_status'] = 1;
        $goods_video_count = Db::name('goods_copywrite')->where($where)->count();
        $interact_video_count = Db::name('interact_copywrite')->where($where)->count();

        $type_list = [
            [
                'name' => '商品文案视频生成',
                'value' => $goods_video_count
            ], [
                'name' => '互动文案视频生成',
                'value' => $interact_video_count
            ]
        ];
        $this->assign('pie_series', json_encode($type_list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '视频生成统计');

        return $this->fetch();
    }
}
